package org.celery.modules.shop.controller;

import com.alibaba.ocean.rawsdk.ApiExecutor;
import com.alibaba.ocean.rawsdk.client.entity.AuthorizationToken;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;

import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.AllArgsConstructor;

import javax.validation.Valid;

import org.celery.common.config.AlibabaProperties;
import org.celery.modules.purchase.entity.Purchase;
import org.celery.modules.purchase.service.IPurchaseService;
import org.celery.modules.shop.entity.ShopDept;
import org.celery.modules.shop.entity.ShopUser;
import org.celery.modules.shop.service.IShopDeptService;
import org.celery.modules.shop.service.IShopUserService;
import org.celery.modules.shopStatics.entity.ShopStaticsDay;
import org.celery.modules.shopStatics.service.IShopStaticsDayService;
import org.celery.modules.ticket.entity.CustomTicket;
import org.celery.modules.ticket.entity.Ticket;
import org.celery.modules.ticket.service.ICustomTicketService;
import org.celery.modules.ticket.service.ITicketService;
import org.springblade.core.log.exception.ServiceException;
import org.springblade.core.mp.support.Condition;
import org.springblade.core.mp.support.Query;
import org.springblade.core.secure.BladeUser;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.utils.*;
import org.springblade.modules.auth.granter.ITokenGranter;
import org.springblade.modules.auth.granter.TokenGranterBuilder;
import org.springblade.modules.auth.granter.TokenParameter;
import org.springblade.modules.auth.utils.TokenUtil;
import org.springblade.modules.system.entity.*;
import org.springblade.modules.system.service.*;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.annotation.RequestParam;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.celery.modules.shop.entity.Shop;
import org.celery.modules.shop.vo.ShopVO;
import org.celery.modules.shop.wrapper.ShopWrapper;
import org.celery.modules.shop.service.IShopService;
import org.springblade.core.boot.ctrl.BladeController;

import java.io.IOException;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 店铺表 控制器
 *
 * @author Celery
 * @since 2023-06-12
 */
@RestController
@AllArgsConstructor
@RequestMapping("celery-shop/shop")
@Api(value = "店铺表", tags = "店铺表接口")
public class ShopController extends BladeController {

    private final IShopService shopService;
    private final ICustomTicketService customTicketService;
    private final AlibabaProperties alibabaProperties;
    private RedisUtil redisUtil;

    /**
     * 详情
     */
    @GetMapping("/detail")
    @ApiOperationSupport(order = 1)
    @ApiOperation(value = "详情", notes = "传入shop")
    public R<ShopVO> detail(Shop shop) {
        Shop detail = shopService.getOne(Condition.getQueryWrapper(shop));
        return R.data(ShopWrapper.build().entityVO(detail));
    }

    /**
     * 分页 店铺表
     */
    @GetMapping("/list")
    @ApiOperationSupport(order = 2)
    @ApiOperation(value = "分页", notes = "传入shop")
    public R<IPage<ShopVO>> list(Shop shop, Query query,
                                 @RequestParam(required = false) @DateTimeFormat(pattern="yyyy-MM-dd") LocalDate dateStart,
                                 @RequestParam(required = false) @DateTimeFormat(pattern="yyyy-MM-dd") LocalDate dateEnd,
                                 BladeUser user) {
        QueryWrapper<Shop> queryWrapper = Condition.getQueryWrapper(shop);
        queryWrapper = shopService.authWrapper(queryWrapper, user);
        if (Func.isNull(queryWrapper)) {
            return R.data(new Page<>());
        }
        if (Func.isNotEmpty(dateStart) && Func.isNotEmpty(dateEnd)) {
            queryWrapper.lambda().between(Shop::getOpenDate, dateStart, dateEnd);
        }
        IPage<Shop> pages = shopService.page(Condition.getPage(query), queryWrapper);
        return R.data(ShopWrapper.build().pageVO(pages));
    }


    /**
     * 自定义分页 店铺表
     */
    @GetMapping("/page")
    @ApiOperationSupport(order = 3)
    @ApiOperation(value = "分页", notes = "传入shop")
    public R<IPage<ShopVO>> page(ShopVO shop, Query query) {
        IPage<ShopVO> pages = shopService.selectShopPage(Condition.getPage(query), shop);
        return R.data(pages);
    }

    /**
     * 新增 店铺表
     */
    @PostMapping("/save")
    @ApiOperationSupport(order = 4)
    @ApiOperation(value = "新增", notes = "传入shop")
    public R save(@Valid @RequestBody Shop shop, BladeUser user) {
        if (Func.isEmpty(shop.getTenantId())) {
            shop.setTenantId(user.getTenantId());
        }
        return R.status(shopService.save(shop));
    }

    /**
     * 修改 店铺表
     */
    @PostMapping("/update")
    @ApiOperationSupport(order = 5)
    @ApiOperation(value = "修改", notes = "传入shop")
    public R update(@Valid @RequestBody Shop shop) {
        return R.status(shopService.updateById(shop));
    }

    /**
     * 新增或修改 店铺表
     */
    @PostMapping("/submit")
    @ApiOperationSupport(order = 6)
    @ApiOperation(value = "新增或修改", notes = "传入shop")
    public R submit(@Valid @RequestBody Shop shop, BladeUser user) {
        if (Func.isEmpty(shop.getTenantId()) && Func.isEmpty(shop.getId())) {
            shop.setTenantId(user.getTenantId());
        }
        IUserService userService = SpringUtil.getBean(IUserService.class);
        User bladeUser = userService.getById(user.getUserId());



        if (Func.isNotEmpty(bladeUser) && Func.isEmpty(shop.getId())) {
            shopService.save(shop);

            List<Long> deptList = Func.toLongList(bladeUser.getDeptId());
            IShopDeptService shopDeptService = SpringUtil.getBean(IShopDeptService.class);
            IShopUserService shopUserService = SpringUtil.getBean(IShopUserService.class);
            deptList.forEach(deptId -> shopDeptService.save(new ShopDept() {{
                setShopId(shop.getId());
                setDeptId(deptId);
            }}));

            shopUserService.save(new ShopUser() {{
                setShopId(shop.getId());
                setUserId(user.getUserId());
            }});
            return R.status(true);
        }
        return R.status(shopService.saveOrUpdate(shop));
    }


    /**
     * 删除 店铺表
     */
    @PostMapping("/remove")
    @ApiOperationSupport(order = 7)
    @Transactional(rollbackFor = Exception.class)
    @ApiOperation(value = "逻辑删除", notes = "传入ids")
    public R remove(@ApiParam(value = "主键集合", required = true) @RequestParam String ids) {
        IPurchaseService purchaseService = SpringUtil.getBean(IPurchaseService.class);
        IShopStaticsDayService shopStaticsDayService = SpringUtil.getBean(IShopStaticsDayService.class);
        ITicketService ticketService = SpringUtil.getBean(ITicketService.class);

        List<ShopStaticsDay> shopStaticsDayList = shopStaticsDayService.list(Wrappers.<ShopStaticsDay>lambdaQuery().in(ShopStaticsDay::getShopId, ids));
        if (Func.isNotEmpty(shopStaticsDayList)) {
            shopStaticsDayService.deleteLogic(shopStaticsDayList.stream().map(ShopStaticsDay::getId).collect(Collectors.toList()));
        }

        List<Shop> shopList = shopService.list(Wrappers.<Shop>lambdaQuery().in(Shop::getId, ids));

        List<Ticket> ticketList = ticketService.list(Wrappers.<Ticket>lambdaQuery().in(Ticket::getUserName, shopList.stream().map(Shop::getResourceOwner).collect(Collectors.toList())));
        if (Func.isNotEmpty(ticketList)) {
            List<Long> ticketIds = ticketList.stream().map(Ticket::getId).collect(Collectors.toList());
            ticketService.deleteLogic(ticketIds);

            List<Purchase> purchaseList = purchaseService.list(Wrappers.<Purchase>lambdaQuery().in(Purchase::getTicketId, ticketIds));
            if (Func.isNotEmpty(purchaseList)) {
                purchaseService.deleteLogic(purchaseList.stream().map(Purchase::getId).collect(Collectors.toList()));
            }
        }

        List<CustomTicket> customTicketList = customTicketService.list(Wrappers.<CustomTicket>lambdaQuery()
                .in(CustomTicket::getShopId, ids)
        );
        if (Func.isNotEmpty(customTicketList)) {
            customTicketService.deleteLogic(customTicketList.stream().map(CustomTicket::getId).collect(Collectors.toList()));
        }

        return R.status(shopService.deleteLogic(Func.toLongList(ids)));
    }

    /**
     * 获取订单列表
     */
    @GetMapping("/custom_list")
    public R<IPage<Shop>> getShopList(Shop shop, Query query) {
        return R.data(shopService.getShopList(shop, query));
    }

    /**
     * 根据id获取订单列表
     */
    @GetMapping("/singleShop")
    public R<Shop> getShopById(@RequestParam Long orderId) {
        return R.data(shopService.getShopById(orderId));
    }

    /**
     * 删除订单列表
     */
    @GetMapping("/delete_shop")
    public R<Boolean> deleteShop(@RequestParam Long shopId) {
        return R.data(shopService.deleteShop(shopId));
    }

    /**
     * 修改订单列表
     */
    @PostMapping("/modify_shop")
    public R<Boolean> modifyShop(@RequestBody Shop shop) {
        return R.data(shopService.modifyShop(shop));
    }


    /**
     * 新增订单列表
     */
    @PostMapping("/add_shop")
    public R<Boolean> addShop(@RequestBody Shop shop) {
        return R.data(shopService.addShop(shop));
    }

    /**
     * 授权绑定
     */
    @PostMapping("/auth")
    @ApiOperation(value = "授权绑定", notes = "传入code")
    public R auth(@Valid @RequestParam(required = false) String code) {
        if (Func.isEmpty(code)) {
            return R.fail("缺少参数, 请重新授权!");
        }

        AuthorizationToken authorizationToken;
        try {
            ApiExecutor apiExecutor = new ApiExecutor(alibabaProperties.getAppKey(), alibabaProperties.getAppSecret());
            authorizationToken = apiExecutor.getToken(code);
        } catch (Exception e) {
            throw new ServiceException("阿里巴巴授权失败!");
        }

        Shop shop = shopService.getOne(Wrappers.<Shop>lambdaQuery()
                .eq(Shop::getAliId, authorizationToken.getAliId())
        );

        if (Func.isEmpty(shop)) {
            shopService.save(new Shop() {{
                setAccessToken(authorizationToken.getAccess_token());
                setAliId(authorizationToken.getAliId());
                setMemberId(authorizationToken.getMemberId());
                setExpiresIn(authorizationToken.getExpires_in());
                setRefreshToken(authorizationToken.getRefresh_token());
                setRefreshTokenTimeout(authorizationToken.getRefresh_token_timeout());
                setResourceOwner(authorizationToken.getResource_owner());
            }});
        }
        return R.data(shop);

    }

    /**
     * 授权绑定
     */
    @PostMapping("/auth-by-aliid")
    @ApiOperation(value = "授权绑定", notes = "传入aliId")
    public R authByAliId(@Valid @RequestParam String aliId) {
        Shop shop = shopService.getOne(Wrappers.<Shop>lambdaQuery()
                .eq(Shop::getAliId, aliId)
        );

        if (Func.isEmpty(shop)) {
            return R.fail(TokenUtil.USER_NOT_FOUND);
        }

        IUserService userService = SpringUtil.getBean(IUserService.class);
        User user = userService.getOne(Wrappers.<User>lambdaQuery().eq(User::getAccount, shop.getResourceOwner()));
        if (Func.isEmpty(user)) {
            throw new ServiceException("用户不存在!");
        }

        String userType = Func.toStr(WebUtil.getRequest().getHeader(TokenUtil.USER_TYPE_HEADER_KEY), TokenUtil.DEFAULT_USER_TYPE);

        TokenParameter tokenParameter = new TokenParameter();
        tokenParameter.getArgs().set("tenantId", user.getTenantId())
                .set("account", user.getAccount())
                .set("password", user.getPassword())
                .set("grantType", "password")
                .set("refreshToken", null)
                .set("userType", userType);

        ITokenGranter granter = TokenGranterBuilder.getGranter("password");
        UserInfo userInfo = granter.grantAli(tokenParameter);
        // 存入redis,user角色
        redisUtil.set("userInfo", userInfo.getUser());
        if (userInfo.getUser() == null) {
            return R.fail(TokenUtil.USER_NOT_FOUND);
        }
        return R.data(TokenUtil.createAuthInfo(userInfo));
    }

    /**
     * 注册
     */
    @PostMapping("/register-by-aliid")
    @Transactional(rollbackFor = Exception.class)
    @ApiOperation(value = "授权绑定", notes = "传入aliId")
    public R registerByAliId(@Valid @RequestParam String aliId) {
        Shop shop = shopService.getOne(Wrappers.<Shop>lambdaQuery()
                .eq(Shop::getAliId, aliId)
        );

        if (Func.isEmpty(shop)) {
            return R.fail("店铺未创建, 请尝试重新授权!");
        }

        if (Func.isNotEmpty(shop) && Func.isNotEmpty(shop.getTenantId())) {
            return R.fail("店铺已经注册账户, 请勿重复操作");
        }

        IUserService userService = SpringUtil.getBean(IUserService.class);
        User user = userService.getOne(Wrappers.<User>lambdaQuery().eq(User::getAccount, shop.getResourceOwner()));
        if (Func.isNotEmpty(user)) {
            throw new ServiceException("用户已注册!如不是本人操作请联系客服");
        }

        ITenantService tenantService = SpringUtil.getBean(ITenantService.class);
        String password = "Aa123456";
        User tenantUser = tenantService.addTenant(shop.getResourceOwner(), password);

        shop.setTenantId(tenantUser.getTenantId());
        shopService.saveOrUpdate(shop);

        String userType = Func.toStr(WebUtil.getRequest().getHeader(TokenUtil.USER_TYPE_HEADER_KEY), TokenUtil.DEFAULT_USER_TYPE);

        TokenParameter tokenParameter = new TokenParameter();
        tokenParameter.getArgs().set("tenantId", tenantUser.getTenantId())
                .set("account", tenantUser.getAccount())
                .set("password", DigestUtil.encrypt(password))
                .set("grantType", "password")
                .set("refreshToken", null)
                .set("userType", userType);

        ITokenGranter granter = TokenGranterBuilder.getGranter("password");
        UserInfo userInfo = granter.grantAli(tokenParameter);
        // 存入redis,user角色
        redisUtil.set("userInfo", userInfo.getUser());
        if (userInfo.getUser() == null) {
            return R.fail(TokenUtil.USER_NOT_FOUND);
        }
        return R.data(TokenUtil.createAuthInfo(userInfo));
    }


    /**
     * 增加返回下拉列表的shop选择
     */
    @GetMapping("/shop_select")
    public R<List<HashMap<String, String>>> getShopSelect(@Valid @RequestParam(required = false) String name, BladeUser user) {
        return R.data(shopService.getShopSelect(name, user));
    }

    /**
     * 获取文件内容
     */
    @GetMapping("/get_file_content")
    public R<ArrayList<String>> getFileContent(String path) throws IOException {
        return R.data(shopService.getFileContent(path));
    }

    /**
     * 获取文件内容
     */
    @GetMapping("/get_custom_properties")
    public R<HashMap<String, String>> getCustomProperties() {
        return R.data(shopService.getCustomProperties());
    }
}


